package com.mogujie.tt.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.DBInterface;
import com.mogujie.tt.DB.entity.DepartmentEntity;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.R;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.ui.base.QZBaseActivity;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.utils.IMUIHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by user on 2015/11/11.
 */
public class DepartmentTwoActivity extends QZBaseActivity {

    private DBInterface dbInterface = DBInterface.instance();//读取本地数据库
    private Map<Integer,UserEntity> userMap = new ConcurrentHashMap<>();//该登录用户下所在的顶级部门底下的所有用户
    private Map<Integer,DepartmentEntity> departmentMap = new ConcurrentHashMap<>();//该登录用户下所在的顶级部门底下的所有部门

    private ArrayList<DepartmentEntity> departmentLevelName = new ArrayList<DepartmentEntity>();//根据部门等级存储部门姓名

    private Object[] group;
    private Object[][]  childItem;

    private LinearLayout mLinearLayout;
    private int mWidth;
    private int count ;
    private MyAdapter myAdapter;
    private ExpandableListView mExpandableListView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();//初始化数据

        LayoutInflater.from(this).inflate(R.layout.tt_activity_depart_two, topContentView);
        showTopInformation("部门");//得到顶级部门值
        initAdapter();
        operationExpandableListView();
        dynamicDisplayDepartment(1);
    }

    private void  initAdapter(){
        myAdapter = new MyAdapter(this);
        myAdapter.dataBinding(group, childItem);
    }

    private void  operationExpandableListView(){

        mExpandableListView =(ExpandableListView) findViewById(R.id.el_list);
        mExpandableListView.setGroupIndicator(null); //去掉前面的箭头图标
        mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                if (childItem[groupPosition][childPosition] instanceof DepartmentEntity) {
                    DepartmentEntity departmentEntity1 = (DepartmentEntity) childItem[groupPosition][childPosition];
                    DepartmentEntity departmentEntity2 = departmentMap.get(departmentEntity1.getParentDepartId());//父部门
                    DepartmentLevelNameRemove(0, 0);//第一种清空方式
                    departmentLevelName.add(departmentEntity2);
                    ResearchersGroupedPoints(departmentEntity2.getDepartLevel() + 1, departmentEntity2.getDepartId());
                    myAdapter.dataBinding(group, childItem);
                    myAdapter.notifyDataSetChanged();
                    dynamicDisplayDepartment(departmentLevelName.size());
                } else if (childItem[groupPosition][childPosition] instanceof UserEntity) {
                    UserEntity userEntity = (UserEntity) childItem[groupPosition][childPosition];
                    IMUIHelper.openUserProfileActivity(DepartmentTwoActivity.this, userEntity.getPeerId());
                }
                return true;
            }

        });
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                // TODO Auto-generated method stub

                if (group[groupPosition] instanceof DepartmentEntity) {
                    return false;
                } else if (group[groupPosition] instanceof UserEntity) {
                    UserEntity userEntity = (UserEntity) group[groupPosition];
                    IMUIHelper.openUserProfileActivity(DepartmentTwoActivity.this, userEntity.getPeerId());
                    return true;// 为ture 就不展开  false就展开
                }
                return true;
            }
        });
        //ExpandableListView中包含多个group，想要展开一个group时，其他group都关闭
        mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < group.length; i++) {
                    if (groupPosition != i) {
                        mExpandableListView.collapseGroup(i);
                    }
                }
            }
        });
        mExpandableListView.setAdapter(myAdapter);
    }

    /**
     * 获得屏幕宽度
     */
    private void getDeviceWidth() {
        DisplayMetrics dm = new DisplayMetrics();// 获得屏幕分辨率
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
    }


    private void dynamicDisplayDepartment(int num) {

        mLinearLayout = (LinearLayout) findViewById(R.id.scrollview_layout);// 实例化线性布局

        mLinearLayout.removeAllViews();// 删除以前的组件（如此保证每次都是horizontalscrollview中只有num个组件）

        for (int i = 0; i < num; i++) {// 在horizontalscrollview中添加num个组件
            int width = mWidth / 3;
            LinearLayout itemLayout = (LinearLayout) LinearLayout.inflate(
                    DepartmentTwoActivity.this, R.layout.scrollview_item, null);// 动态实例化一个LinearLayout
            itemLayout.setLayoutParams(new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT));// 设置宽度为一张屏幕显示三个组件

            itemLayout.setGravity(Gravity.CENTER_VERTICAL);// 设置垂直居中
            TextView mTextView = (TextView) itemLayout.findViewById(R.id.textview);
            mLinearLayout.addView(itemLayout);

            if(i == num -1) {
                if(i == 0){
                    mTextView.setTextColor(getResources().getColor(R.color.black));
                }else{
                    mTextView.setBackground(getResources().getDrawable(R.drawable.textviewgreen2));
                    mTextView.setTextColor(getResources().getColor(R.color.red));
                }
            } else {
                mTextView.setTextColor(getResources().getColor(R.color.black));
            }

            final int id = i;
            mTextView.setText(departmentLevelName.get(i).getDepartName().toString());

            mTextView.setOnClickListener(new View.OnClickListener() {//第几个id

                @Override
                public void onClick(View arg0) {
                    count = id+1;//按下去要显示多少
                    DepartmentEntity departmentEntity = departmentLevelName.get(id);
                    ResearchersGroupedPoints(departmentEntity.getDepartLevel()+1,departmentEntity.getDepartId());
                    myAdapter.dataBinding(group, childItem);
                    myAdapter.notifyDataSetChanged();
                    DepartmentLevelNameRemove(1,count);
                    dynamicDisplayDepartment(count);
                }
            });
        }
    }

    /**
     * 初始化数据
     */
    private void  initData(){
        getDeviceWidth();
        List<DepartmentEntity> deptlist = dbInterface.loadAllDept();

        List<UserEntity> userlist = dbInterface.loadAllUsers();

        for(UserEntity userInfo:userlist){
            userMap.put(userInfo.getPeerId(), userInfo);
        }

        for(DepartmentEntity deptInfo:deptlist){
            departmentMap.put(deptInfo.getDepartId(), deptInfo);
        }

        departmentLevelName.add(departmentMap.get(departmentMap.get(IMLoginManager.instance().getLoginDeptId()).getHostDepartId()));
        ResearchersGroupedPoints(2,1);//绑定数据
    }

    private  String  GetTopDepartment(){

       String string = departmentMap.get(departmentMap.get(IMLoginManager.instance().getLoginDeptId()).getHostDepartId()).getDepartName().toString();
        return  string;

    }

    /**
     * 分组分人员
     * @param departmentLevel
     * @param userDepartmentId
     */
    private void ResearchersGroupedPoints(int departmentLevel,int userDepartmentId ){
         Object[] group;
         Object[][]  childItem ;
        Object[] groupTemp =  new  Object[100];//临时
        Object[][]  childItemTemp = new Object[100][100];//临时
        int i =0;
        if(departmentLevel <= 0){
            return;
        }
        List<UserEntity> userList = new ArrayList<>(userMap.values());
        List<DepartmentEntity>  departList = new ArrayList<>(departmentMap.values());

        for(DepartmentEntity departmentEntity: departList){
            if(departmentEntity.getDepartLevel() == departmentLevel && departmentEntity.getParentDepartId() == userDepartmentId){
                groupTemp[i++] = departmentEntity;
            }
        }
        final int departmentNumber = i;
        for(UserEntity userEntity:userList){
            if(userEntity.getDepartmentId() == userDepartmentId){
                groupTemp[i++] = userEntity;
            }
        }

        group =new Object[i];
        for(int ii =0;ii <i;ii++ ){
            group[ii] = groupTemp[ii];
        }

        int z;
        ArrayList<Integer> array = new ArrayList<Integer>();//放二维数据个数
        for(int j =0;j <departmentNumber;j++){
             z =0;
            if(groupTemp[j] instanceof DepartmentEntity){
              DepartmentEntity departmentEntity1 = (DepartmentEntity)group[j];

                for(DepartmentEntity departmentEntity2:departList){
                    if(departmentEntity1.getDepartId() == departmentEntity2.getParentDepartId()){
                        childItemTemp[j][z++] = departmentEntity2;
                    }
                }

                for(UserEntity userEntity2:userList){
                    if(departmentEntity1.getDepartId() == userEntity2.getDepartmentId()){
                        childItemTemp[j][z++] = userEntity2;
                    }
                }
           }
            array.add(z);
        }

        childItem =new Object[departmentNumber][];


        for(int ii =0;ii< departmentNumber;ii++)
        {
            childItem[ii] = new Object[array.get(ii)];
        }

        for(int ii =0;ii < childItem.length ;ii++){
            for(int jj=0;jj < childItem[ii].length;jj++){
                childItem[ii][jj] = childItemTemp[ii][jj];
            }

        }

        this.group =group;
       this.childItem =childItem;
     //  ValidationGroupingInformationIsCorrect();
    }

    /**
     * 验证分组分人信息是否正确
     */
    private void ValidationGroupingInformationIsCorrect(){

        Log.v("DepartmentTwoActivityc","group.length ="+group.length);
        for(int i=0;i<group.length;i++){
            if(group[i] instanceof DepartmentEntity){
                DepartmentEntity departmentEntity =(DepartmentEntity)group[i];
                Log.v("DepartmentTwoActivityc","departmentEntity Name = "+departmentEntity.getDepartName());
            }

            if(group[i] instanceof UserEntity){
                UserEntity userEntity =(UserEntity)group[i];
                Log.v("DepartmentTwoActivityc","userEntity Name = "+userEntity.getMainName());
            }
        }

        for(int i =0 ;i<group.length;i++){
            if(group[i] instanceof DepartmentEntity) {
                Log.v("DepartmentTwoActivityc", "--------------------------");
                for (int j = 0; j < childItem[i].length; j++) {
                    if (childItem[i][j] instanceof DepartmentEntity) {
                        DepartmentEntity departmentEntity = (DepartmentEntity) childItem[i][j];
                        Log.v("DepartmentTwoActivityc", "departmentEntity Name = " + departmentEntity.getDepartName());
                    }
                    if (childItem[i][j] instanceof UserEntity) {
                        UserEntity userEntity = (UserEntity) childItem[i][j];
                        Log.v("DepartmentTwoActivityc", "userEntity Name = " + userEntity.getMainName());
                    }
                }
            }
        }
    }

    private  class MyAdapter extends BaseExpandableListAdapter {

        private Context context;
        private Object parentNumber[];
        private Object childrenNumber[][];

        public void dataBinding(Object parentNumber[],Object childrenNumber[][]){
            this.parentNumber = parentNumber;
            this.childrenNumber = childrenNumber;
        }


        public MyAdapter(Context context){
            this.context = context;

        }

        @Override
        public int getGroupCount() {
            // TODO Auto-generated method stub
            return parentNumber.length;
        }


        @Override
        public int getChildrenCount(int groupPosition) {
            // TODO Auto-generated method stub
            return childrenNumber[groupPosition].length;
        }

        @Override
        public Object getGroup(int groupPosition) {
            // TODO Auto-generated method stub
            return parentNumber[groupPosition];
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return childrenNumber[groupPosition][childPosition];
        }

        @Override
        public long getGroupId(int groupPosition) {
            // TODO Auto-generated method stub
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view =null;
            if(convertView == null){
                view = LayoutInflater.from(context).inflate(R.layout.item_depart_group, null);

            }else{
                view = convertView;
            }
            TextView textView =(TextView)view.findViewById(R.id.textView1);
            ImageView imageView = (ImageView)view.findViewById(R.id.imageView1);
            IMBaseImageView imBaseImageView =(IMBaseImageView)view.findViewById(R.id.iv_avatar);

            if(parentNumber[groupPosition] instanceof DepartmentEntity ){
              DepartmentEntity departmentEntity =(DepartmentEntity)parentNumber[groupPosition];
                textView.setText(departmentEntity.getDepartName().toString());
                imBaseImageView.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
            }
            if(parentNumber[groupPosition] instanceof UserEntity ){
                UserEntity userEntity =(UserEntity)parentNumber[groupPosition];
                textView.setText(userEntity.getMainName().toString());
                imBaseImageView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                imBaseImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
                imBaseImageView.setCorner(15);
                imBaseImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
                imBaseImageView.setImageUrl(userEntity.getAvatar());
            }
            return view;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view = null;
            if(convertView == null){
                view = LayoutInflater.from(context).inflate(R.layout.item_depart_child, null);
            }else{
                view = convertView;
            }
            TextView textView =(TextView)view.findViewById(R.id.textView1);
            ImageView imageView = (ImageView)view.findViewById(R.id.imageView1);
            IMBaseImageView imBaseImageView =(IMBaseImageView)view.findViewById(R.id.iv_avatar);
            if(childrenNumber[groupPosition][childPosition] instanceof DepartmentEntity ){
                DepartmentEntity departmentEntity =(DepartmentEntity)childrenNumber[groupPosition][childPosition];
                textView.setText(departmentEntity.getDepartName().toString());
                imBaseImageView.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
            }
            if(childrenNumber[groupPosition][childPosition] instanceof UserEntity ){
                UserEntity userEntity =(UserEntity)childrenNumber[groupPosition][childPosition];
                textView.setText(userEntity.getMainName().toString());
                imBaseImageView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                imBaseImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
                imBaseImageView.setCorner(15);
                imBaseImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
                imBaseImageView.setImageUrl(userEntity.getAvatar());
            }

            return view;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return true;
        }


    }




    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test) {
        if (test == null) {
            return;
        }
        setTopBarDisplay();

        setCenterText(test);
    }


    /**
     * 退出Activity
     *
     * @param view
     */
    public void onClickExit(View view) {
        switch (view.getId()) {
            case R.id.left_out_button:
                DepartmentTwoActivity.this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 部门等级姓名清空
     * @param choose
     * @param number
     */
   private void  DepartmentLevelNameRemove(int choose,int number ){
       if(choose == 0) {
           ArrayList<DepartmentEntity> departmentEntities = new ArrayList<DepartmentEntity>();
           for (DepartmentEntity departmentEntity : departmentLevelName) {
               departmentEntities.add(departmentEntity);
           }
           departmentLevelName.clear();
           departmentLevelName = departmentEntities;
       }else if(choose ==1){
           ArrayList<DepartmentEntity> departmentEntities = new ArrayList<DepartmentEntity>();
           for(int i= 0;i< number;i++){
               departmentEntities.add(departmentLevelName.get(i));
           }
           departmentLevelName.clear();
           departmentLevelName =departmentEntities;
       }

   }
}
